import grails.util.Environment
import org.springframework.orm.hibernate3.HibernateTemplate
import org.springframework.beans.SimpleTypeConverter
import org.springframework.web.context.support.WebApplicationContextUtils
import mz.matafe.bolao.*

class BootStrap {

    def passwordEncoder

    def init = { servletContext ->

        switch(Environment.current) {
            case Environment.DEVELOPMENT:
            println "### BootStrap init ###"
            createRolesIfRequired()
            createAdminUserIfRequired()


            //createRolesAndUsersIfRequired()
            createCupIfRequired()
            createGroupsIfRequired()
            createTeamsIfRequired()
            createMatchesIfRequired()
            //createBetsIfRequired()
            break;
            case Environment.PRODUCTION:
            // nothing todo
            break
        }
    }
     
    def destroy = {
        println "### BootStrap detroy ###"
    }

    void printHeader(String msg){
        println '=' * 20 + msg + '=' * 20
    }

    void createRolesIfRequired(){
        if (Role.count() == 0) {
            printHeader(' Creating ROLES ')
            def adminRole = new Role(code: 'ROLE_ADMIN',
                description: 'Administador').save()
            def supervisorRole = new Role(code: 'ROLE_SUPERVISOR',
                description: 'Supervisor').save()
            def userRole = new Role(code: 'ROLE_USER',
                description: 'Usuário').save()
        }
    }
    
    void createAdminUserIfRequired(){
        if (Role.count() > 0) {
            printHeader(' Creating ROLES ')
            def adminRole = Role.findByCode('ROLE_ADMIN');
            def supervisorRole = Role.findByCode('ROLE_SUPERVISOR');
            def userRole = Role.findByCode('ROLE_USER');
            //println 'Role ROLE_ADMIN created'
            //println 'Role ROLE_SUPERVISOR created'
            //println 'Role ROLE_USER created'
            if (!User.findByUsername("admin")) {
                printHeader(' Creating USERS ')
                String passwd = passwordEncoder.encodePassword('admin', null)
                def admin = new User(username: 'admin', password: passwd,
                    firstname: 'Administrador', surname: 'Sistema',
                    email: 'matafe@gmail.com',
                    contactNumber: '+258846819000' ).save()
                println 'User admin/admin created'
                println "Adding user 'admin' to ROLE_ADMIN"
                adminRole.addToUsers(admin)
                println "Adding user 'admin' to ROLE_USER"
                userRole.addToUsers(admin)
                println "Adding user 'admin' to ROLE_SUPERVISOR"
                supervisorRole.addToUsers(admin)
            }else{
                println 'The user admin already exists!'
            }
        }else{
            println 'No user created, because there arent rules!'
        }
    }
    
    void createRolesAndUsersIfRequired(){
        if (Role.count() == 0) {
            printHeader(' Creating ROLES ')
            def adminRole = new Role(code: 'ROLE_ADMIN',
                description: 'Administador').save()
            def supervisorRole = new Role(code: 'ROLE_SUPERVISOR',
                description: 'Supervisor').save()
            def userRole = new Role(code: 'ROLE_USER',
                description: 'Usuário').save()
            //println 'Role ROLE_ADMIN created'
            //println 'Role ROLE_SUPERVISOR created'
            //println 'Role ROLE_USER created'
            if (!User.findByUsername("admin")) {
                printHeader(' Creating USERS ')
                String passwd = passwordEncoder.encodePassword('admin', null)
                def admin = new User(username: 'admin', password: passwd,
                    firstname: 'Administrador', surname: 'Sistema',
                    email: 'matafe@gmail.com',
                    contactNumber: '+258846819000' ).save()
                println 'User admin/admin created'
                passwd = passwordEncoder.encodePassword('super', null)
                def supervisor = new User(username: 'super', password: passwd,
                    firstname: 'Supervisor', surname: 'Sistema').save()
                println 'User super/super created'
                passwd = passwordEncoder.encodePassword('user1', null)
                def user1 = new User(username: 'user1', password: passwd,
                    firstname: 'User1', surname: 'Teste1').save()
                println 'User user1/user1 created'
                passwd = passwordEncoder.encodePassword('user2', null)
                def user2 = new User(username: 'user2', password: passwd,
                    firstname: 'User2', surname: 'Teste2').save()
                println 'User user2/user2 created'
                println "Adding user 'admin' to ROLE_ADMIN"
                adminRole.addToUsers(admin)
                println "Adding user 'admin' to ROLE_USER"
                userRole.addToUsers(admin)
                println "Adding user 'admin' to ROLE_SUPERVISOR"
                supervisorRole.addToUsers(admin)
                println "Adding user 'super' to ROLE_SUPERVISOR"
                supervisorRole.addToUsers(supervisor)
                println "Adding user 'super' to ROLE_USER"
                userRole.addToUsers(supervisor)
                println "Adding user 'user1' to ROLE_USER"
                userRole.addToUsers(user1)
                println "Adding user 'user2' to ROLE_USER"
                userRole.addToUsers(user2)
            }
        }
    }

    /** Create a cup*/
    void createCupIfRequired() {
        if (Cup.count() == 0) {
            printHeader(' Creating CUPS ')
            def adminUser = User.findByUsername("admin");
            def cup = new Cup(year: 2010, venue: 'Africa do Sul',
                createdBy: adminUser, updatedBy: adminUser).save()
        } else {
            println "Existing a cup, skipping creation"
        }
    }

    /** Create the groups*/
    void createGroupsIfRequired() {
        if (Group.count() == 0) {
            printHeader(' Creating GROUPS ')
            def adminUser = User.findByUsername("admin");
            def cup = Cup.findByYear(2010);
            def groups = ['A','B','C','D','E','F','G','H']
            //println 'Creating groups: ' + groups
            groups.each{
                new Group(name:"$it", cup: cup, createdBy: adminUser,
                    updatedBy: adminUser).save()
            }
        } else {
            println "Existing groups, skipping creation"
        }
    }

    /** Create some teams*/
    void createTeamsIfRequired() {
        if (Team.count() == 0) {
            printHeader(' Creating TEAMS ')
            def adminUser = User.findByUsername("admin");
            def groupA = Group.findByName('A');
            def teamDetailsA = new TeamDetails(played:0,won:0,draw:0,
                lost:0,goalsFor:0,goalsAgainst:0,points:0)
            def teamNamesA = ['Africa do Sul','Mexico','Uruguai','França']
            //println 'Creating teams of group : ' + groupA.name
            teamNamesA.each{
                new Team(name:"$it", group: groupA,
                    teamDetails: teamDetailsA, createdBy: adminUser,
                    updatedBy: adminUser ).save()
            }
            def groupB = Group.findByName('B');
            def teamDetailsB = new TeamDetails(played:0,won:0,draw:0,
                lost:0,goalsFor:0,goalsAgainst:0,points:0)
            def teamNamesB = ['Argentina','Nigeria','Coreia do Sul','Grecia']
            //println 'Creating teams of group : ' + groupB.name
            teamNamesB.each{
                new Team(name:"$it", group: groupB,
                    teamDetails: teamDetailsB, createdBy: adminUser,
                    updatedBy: adminUser ).save()
            }
        } else {
            println "Existing team, skipping creation"
        }
    }

    /** Create some matches*/
    void createMatchesIfRequired() {
        if (Match.count() == 0) {
            printHeader(' Creating MATCHES ')
            def adminUser = User.findByUsername("admin");
            def groupA = Group.findByName('A');
            def teamsA = Team.findAllByGroup(groupA).toList();
            def match1 = new Match(matchNumber: 1, matchDate: new Date()+1,
                venue: 'Johannesburg - JSC', team1: teamsA[0],
                team2: teamsA[1], createdBy: adminUser, updatedBy: adminUser).save()
            //println "$match1 created"
            def match2 = new Match(matchNumber: 2, matchDate: new Date()+2,
                venue: 'Cape Town', team1: teamsA[2],
                team2: teamsA[3], createdBy: adminUser, updatedBy: adminUser).save()
            //println "$match2 created"
            def groupB = Group.findByName('B');
            def teamsB = Team.findAllByGroup(groupB).toList();
            def match3 = new Match(matchNumber: 3, matchDate: new Date()+1,
                venue: 'Johannesburg - JSC', team1: teamsB[0],
                team2: teamsB[1], createdBy: adminUser, updatedBy: adminUser).save()
            //println "$match3 created"
            def match4 =  new Match(matchNumber: 4, matchDate: new Date()+2,
                venue: 'Cape Town', team1: teamsB[2],
                team2: teamsB[3], createdBy: adminUser, updatedBy: adminUser).save()
            //println "$match4 created"
        } else {
            println "Existing matches, skipping creation"
        }
    }

    /** Create some bets*/
    void createBetsIfRequired() {
        if (Bet.count() == 0) {
            printHeader(' Creating BETS ')
            def user1 = User.findByUsername('user1')
            def match1 = Match.get(1);
            def match2 = Match.get(2);
            def match3 = Match.get(3);
            def bet1 = new Bet(match:match1,score1:0,score2:0)//0x0
            def bet2 = new Bet(match:match2,score1:0,score2:1)//0x1
            def bet3 = new Bet(match:match3,score1:1,score2:0)//1x0
            
            user1.addToBets(bet1).save()
            user1.addToBets(bet2).save()
            user1.addToBets(bet3).save()

            println "$user1 bets:"
            user1.bets.each{
                println "$it"
            }

            def user2 = User.findByUsername('user2')
            bet1 = new Bet(match:match1,score1:2,score2:0)//2x0
            bet2 = new Bet(match:match2,score1:3,score2:0)//3x0
            bet3 = new Bet(match:match3,score1:4,score2:0)//4x0
            user2.addToBets(bet1).save()
            user2.addToBets(bet2).save()
            user2.addToBets(bet3).save()

            println "$user2 bets:"
            user2.bets.each{
                println "$it"
            }
            
        } else {
            println "Existing bets, skipping creation"
        }
    }

}